#import "MHLazyTableImages.h"
#import "MHImageCache.h"

@implementation UITableViewCell (MHLazyTableImages)


- (void)didLoadLazyImage:(UIImage*)theImage
{
	if (theImage != nil)
		self.imageView.image = theImage;
}

@end

@implementation MHLazyTableImages
@synthesize noNeedDownloadRow;
 
@synthesize delegate, tableView, placeholderImage;

- (void)dealloc
{
	[placeholderImage release];
	[super dealloc];
}

- (UIImage*)imageForURL:(NSURL*)url
{
	return [[MHImageCache sharedInstance] cachedImageWithURL:url];
}

- (void)startDownload:(NSURL*)url indexPath:(NSIndexPath*)indexPath
{
	[[MHImageCache sharedInstance] imageFromURL:url cacheInFile:NO usingBlock:^(UIImage* image)
	{
		if (tableView != nil)
		{
			if (image != nil && [delegate respondsToSelector:@selector(postProcessLazyImage:forIndexPath:)])
			{
				UIImage* newImage = [delegate postProcessLazyImage:image forIndexPath:indexPath];
				if (newImage != image)
				{
					[[MHImageCache sharedInstance] cacheImage:newImage withURL:url];
					image = newImage;
				}
			}

			id<MHLazyTableImageCell> cell = [tableView cellForRowAtIndexPath:indexPath];
			[cell didLoadLazyImage:image];
		}
	}];
}

- (void)addLazyImageForCell:(id<MHLazyTableImageCell>)cell withIndexPath:(NSIndexPath*)indexPath
{
	NSURL* url = [delegate lazyImageURLForIndexPath:indexPath];
	if (url != nil)
	{
		UIImage* image = [self imageForURL:url];
		if (image != nil)
		{
			[cell didLoadLazyImage:image];
		}
		else
		{
			[cell didLoadLazyImage:self.placeholderImage];

			// Defer new downloads until scrolling ends
			if (tableView.dragging == NO && tableView.decelerating == NO)
				[self startDownload:url indexPath:indexPath];
		}
	}
}

- (void)loadImagesForOnscreenRows
{
	NSArray* visiblePaths = [tableView indexPathsForVisibleRows];
	for (NSIndexPath* indexPath in visiblePaths)
	{
        if (indexPath.row<noNeedDownloadRow) {
            NSURL* url = [delegate lazyImageURLForIndexPath:indexPath];
            if (url != nil)
            {
                UIImage* image = [self imageForURL:url];
                if (image == nil)
                {
                    // NOTE: scrolling may trigger an image lookup several times
                    // for the same index path. The image cache already knows how
                    // to handle multiple requests for the same image, but we could
                    // save some overhead by keeping track of which index-paths are
                    // currently downloading images.
                    [self startDownload:url indexPath:indexPath];
                }
            }
        }
	}
}

- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate
{
	// Load images for all on-screen rows when scrolling is finished
	if (!decelerate)
		[self loadImagesForOnscreenRows];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
    [self loadImagesForOnscreenRows];
}



@end
